//index.js
//获取应用实例

const app = getApp();

const pushModeMap = {
  '标清': 'SD',
  '高清': 'HD',
  '超清': 'FHD',
};

Page({
  data: {
    pushURL: 'rtmp://ws.upstream.huya.com/huyalive/1421571180-1421571180-6592380486042786020-2295592560-10057-A-1534908285-1',
    pushMode: 'HD',
    pushModeText: '高清',
    active: true,
    magic: true,
    pushState: 'stop', // stop pushing pause pending
  },

  onLoad: function (option) {
    this.liveTitle = '郑州飞道-wxappLive';
    wx.showShareMenu({
      withShareTicket: true,
    });
    this.pushContext = wx.createLivePusherContext();
  },

  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
  },

  onHide() {
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
  },

  onShareAppMessage() {
    return {
      title: `${this.liveTitle}`,
      success: () => {

      }
    };
  },

  onViewTap() {
    this.setData({ active: !this.data.active });
  },

  onModeTap() {
    const list = ['标清', '高清', '超清'];
    wx.showActionSheet({
      itemList: list,
      success: (res) => {
        this.setData({ pushMode: pushModeMap[list[res.tapIndex]], pushModeText: list[res.tapIndex] });
      },
    })
  },

  onMagicTap() {
    this.setData({ magic: !this.data.magic });
  },

  onCloseTap() {
    wx.navigateBack();
  },

  onSwitchCamera() {
    this.pushContext.switchCamera();
  },

  startPush() {
    this.setData({ pushState: 'pending' });
    this.pushContext.start({
      success: () => {
        app.sendWsMsg && app.sendWsMsg({ type: 'live-status-change' });
        console.log('send', app.sendWsMsg);
        this.setData({ pushState: 'pushing' });
      },
      fail: () => {
        wx.showToast({ title: '推流开始失败' });
        this.setData({ pushState: 'stop' });
      },
    });
  },

  statechange(e) {
    switch (e.detail.code) {
      case -1307:
        wx.showToast({ title: '和远程服务器失去连接', icon: 'none' });
        break;
      case 3004:
        wx.showToast({ title: '远程服务器主动断开连接', icon: 'none' });
        break;
      default:
        break;
    }
    console.log('live-player code:', e.detail.code)
  },

  onUnload() {
    this.pushContext.stop();
  },
})
